<template>
  <div
    class="app-container"
    style="padding-right: 80px; background: #fff; width: 1480px"
  >
    <div class="box-container">
      <div style="border-bottom: 1px solid #ddd; margin-bottom: 10px">
        <el-radio-group v-model="showType" style="gap: 40px">
          <el-radio-button :label="1">招生信息</el-radio-button>
          <el-radio-button :label="2" style="border-left: 1px solid #dcdfe6"
            >批次时间</el-radio-button
          >
        </el-radio-group>
      </div>
      <el-form
        class="box-container"
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-if="showType == 1"
        label-width="68px"
      >
        <el-form-item label="进修科目" prop="registerDeptId">
          <el-select
            v-model="queryParams.registerDeptId"
            placeholder="请选择进修科目"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in registerDeptList"
              :key="index"
              :label="item.registerDeptName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="招生类型" prop="registerTypeId" v-if="false">
          <el-select
            v-model="queryParams.registerTypeId"
            placeholder="请选择招生类型"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in registerTypeList"
              :key="index"
              :label="item.registerTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="招生批次" prop="batchNameList">
          <el-select
            v-model="queryParams.batchNameList"
            placeholder="请选择招生批次"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in registerBatchList"
              :key="index"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="招生状态" prop="needOpen">
          <el-select
            v-model="queryParams.needOpen"
            placeholder="选择招生状态"
            clearable
            @change="handleQuery"
          >
            <el-option label="全部" value="" />
            <el-option label="已开启" value="1" />
            <el-option label="已关闭" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8" v-if="showType == 1">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['business:registerNeed:add']"
            >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['business:registerNeed:edit']"
            >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['business:registerNeed:remove']"
            >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['business:registerNeed:export']"
            >导出
          </el-button>
        </el-col>
        <!-- <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar> -->
      </el-row>
    </div>

    <div class="box-container" v-if="showType == 1">
      <div class="custom-table">
        <el-checkbox
          v-model="AllCheck"
          @change="handleSelectionChangeAll"
          style="transform: scale(1.2); margin-bottom: 20px; margin-left: 20px"
          >全选</el-checkbox
        >
        <div
          class="custom-dept"
          v-for="(row, index) in registerNeedList"
          :key="index"
        >
          <div class="colc title">
            <el-checkbox
              v-model="row.check"
              style="transform: scale(1.2); margin-right: 10px"
              @change="handleSelectionChange($event, index)"
            />
            <span style="color: #000">{{ row.registerDeptName }}</span>
            <div class="desc" style="margin-left: 20px">{{ row.deptDesc }}</div>
          </div>
          <div class="colc w">
            <div
              class="col"
              style="display: flex; flex-direction: column; align-items: center"
            >
              <span>
                {{ row.durationNameList || "" }}
              </span>
              <div class="desc">进修期限</div>
            </div>
            <div
              class="col"
              style="display: flex; flex-direction: column; align-items: center"
            >
              <div>
                <el-popover
                  placement="top-start"
                  title=""
                  width="250"
                  v-for="(item, index) in (row.batchNameList || '').split(',')"
                  :key="index"
                  trigger="hover"
                  :content="'时间：' + row.batchDateList.split(',')[index]"
                >
                  <el-button slot="reference" type="text" style="color: #000">{{
                    index === (row.batchNameList || "").split(",").length - 1
                      ? item
                      : item + ","
                  }}</el-button>
                </el-popover>
              </div>
              <div class="desc">招生批次</div>
            </div>
            <div
              class="col"
              style="display: flex; flex-direction: column; align-items: center"
            >
              <span>
                {{ row.registerEnter || "-" }}
              </span>
              <div class="desc">最低录取资格</div>
            </div>
          </div>
          <div class="colc status">
            <div class="desc">招生状态</div>
            <el-switch
              v-model="row.needOpen"
              :active-value="1"
              :inactive-value="0"
              active-text=""
              inactive-text=""
              @change="handleNeedStatusChange(row)"
            >
            </el-switch>
          </div>
          <div class="colc func">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(row)"
              v-hasPermi="['business:registerNeed:edit']"
              >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(row)"
              v-hasPermi="['business:registerNeed:remove']"
              >删除
            </el-button>
          </div>
        </div>
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改招生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form1" :model="form" :rules="rules" label-width="150px">
        <div style="margin-bottom: 15px">
          <el-steps :active="stepActive" simple>
            <el-step icon="el-icon-edit" v-if="!isSecretary">
              <div slot="title" style="font-size: 18px; font-weight: bolder">
                招生信息
              </div>
            </el-step>
            <el-step icon="el-icon-edit">
              <div slot="title" style="font-size: 18px; font-weight: bolder">
                科室简介
              </div>
            </el-step>
            <el-step icon="el-icon-edit">
              <div slot="title" style="font-size: 18px; font-weight: bolder">
                招生要求
              </div>
            </el-step>
          </el-steps>
        </div>
        <div v-if="stepActive == 1">
          <el-form-item label="进修科目" prop="registerDeptId">
            <el-select
              v-model="form.registerDeptId"
              placeholder="请选择进修科目"
              filterable
              clearable
              style="width: 100%"
              @change="handleDeptChange"
            >
              <el-option
                v-for="(item, index) in registerDeptList"
                :key="index"
                :label="item.registerDeptName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="招生类型" prop="registerTypeId" v-if="false">
            <el-select
              v-model="form.registerTypeId"
              placeholder="请选择招生类型"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in registerTypeList"
                :key="index"
                :label="item.registerTypeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="最低录取资格" prop="registerEnter">
            <el-input
              v-model="form.registerEnter"
              placeholder="请输入最低录取资格"
            />
          </el-form-item>
          <el-form-item label="招生批次" prop="batchNameList">
            <el-select
              v-model="batchList"
              placeholder="请选择招生批次"
              multiple
              filterable
              clearable
              style="width: 100%"
              @change="batchNameListChange"
            >
              <el-option
                v-for="(item, index) in registerBatchList"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="进修期限"
            :prop="batchList == '无' ? '' : 'durationNameList'"
          >
            <el-select
              v-model="durationList"
              placeholder="请选择进修期限"
              :disabled="batchList.includes('无')"
              multiple
              filterable
              clearable
              style="width: 100%"
              @change="durationNameListChange"
            >
              <el-option
                v-for="(item, index) in registerDurationList"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
            <el-button
              type="primary"
              size="mini"
              @click="customOpen"
              style="margin-top: 15px"
              :disabled="batchList.includes('无')"
              >添加自定义</el-button
            >
          </el-form-item>
          <div v-if="durationNameList.length > 0">
            <div
              style="
                padding: 10px;
                margin-bottom: 10px;
                background-color: #f5f7fa;
              "
            >
              <el-form-item
                v-for="(item, index) in durationNameList"
                :key="index"
                :label="item.name + '进修费用'"
              >
                <div style="width: 300px">
                  <el-input
                    type="number"
                    v-model="item.money"
                    :placeholder="'请输入' + item.name + '进修费用'"
                  />
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
        <div v-if="stepActive == 2">
          <el-form-item label="科室图片">
            <image-upload :limit="1" v-model="form.deptPicture" />
          </el-form-item>
          <el-form-item label="科室视频">
            <file-upload
              :limit="1"
              v-model="form.deptVideo"
              :file-type="['mp4']"
            />
          </el-form-item>
          <el-form-item label="科室简介">
            <el-input
              :rows="10"
              v-model="form.deptDesc"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </div>
        <div v-if="stepActive == 3">
          <el-form-item label="招生要求">
            <el-input
              :rows="20"
              v-model="form.registerCondition"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="stepActive > (!isSecretary ? 1 : 2)"
          type="primary"
          @click="stepActive--"
          >上一步</el-button
        >
        <el-button v-if="stepActive < 3" type="primary" @click="nextStep"
          >下一步</el-button
        >
        <el-button v-if="stepActive == 3" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="添加自定义"
      :visible.sync="customShow"
      width="300px"
      append-to-body
    >
      <el-input v-model="customDay" type="number">
        <template slot="append">天</template>
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="customShow = false">取 消</el-button>
        <el-button type="primary" @click="customSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批次时间 -->
    <div v-if="showType == 2" style="padding: 20px; font-size: 16px">
      <!-- Header -->
      <div style="display: flex; font-weight: bold; margin-bottom: 20px">
        <div style="width: 150px; display: flex; justify-content: center">
          状态
        </div>
        <div style="width: 150px; display: flex; justify-content: center">
          年度
        </div>
        <div style="width: 150px; display: flex; justify-content: center">
          招生批次
        </div>
        <div style="width: 300px; display: flex; justify-content: center">
          开始报名时间
        </div>
        <div style="width: 300px; display: flex; justify-content: center">
          结束报名时间
        </div>
      </div>
      <!-- Rows -->
      <div
        v-for="(item, index) in batchDateList"
        :key="index"
        style="display: flex; align-items: center; margin-bottom: 16px"
      >
        <div style="width: 150px; display: flex; justify-content: center">
          <el-switch
            v-model="item.registerStatus"
            :active-value="1"
            :inactive-value="0"
            active-text=""
            inactive-text=""
            @change="handleStatusChange(item)"
          >
          </el-switch>
        </div>
        <div
          style="
            width: 150px;
            display: flex;
            align-items: center;
            justify-content: center;
          "
        >
          <span>{{ item.registerYear }}</span>
          <i
            class="el-icon-edit"
            @click="handleUpdateYear(item)"
            style="cursor: pointer; margin-left: 15px"
          ></i>
        </div>
        <div style="width: 150px; display: flex; justify-content: center">
          {{ item.batch }}
        </div>
        <div
          style="
            width: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
          "
        >
          <span>{{ item.startTime }}</span>
          <i
            class="el-icon-edit"
            @click="handleUpdateTime(item, 'startTime')"
            style="cursor: pointer; margin-left: 15px"
          ></i>
        </div>
        <div
          style="
            width: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
          "
        >
          <span>{{ item.endTime }}</span>
          <i
            class="el-icon-edit"
            @click="handleUpdateTime(item, 'endTime')"
            style="cursor: pointer; margin-left: 15px"
          ></i>
        </div>
      </div>
    </div>

    <!-- 修改批次时间对话框 -->
    <el-dialog
      title="修改批次时间"
      :visible.sync="timePickerShow"
      width="30%"
      append-to-body
    >
      <el-date-picker
        v-model="currentBatchItem[currentBatchItem.type]"
        type="date"
        placeholder="选择日期"
        format="yyyy/MM/dd"
        value-format="yyyy/MM/dd"
        style="width: 100%"
      >
      </el-date-picker>
      <div slot="footer" class="dialog-footer">
        <el-button @click="timePickerShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmUpdateTime">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改年度对话框 -->
    <el-dialog
      title="修改年度"
      :visible.sync="yearPickerShow"
      width="30%"
      append-to-body
    >
      <el-input
        v-model.number="currentYearItem.registerYear"
        type="number"
        placeholder="请输入年度"
        style="width: 100%"
        :min="2000"
        :max="2100"
      >
        <template slot="append">年</template>
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="yearPickerShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmUpdateYear">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import { listAllRegisterDept } from "@/api/business/registerDept";
import {
  addRegisterNeed,
  batchListAll,
  delRegisterNeed,
  getRegisterNeed,
  listRegisterNeed,
  updateBatchTime,
  updateRegisterNeed,
} from "@/api/business/registerNeed";
import { listAllRegisterType } from "@/api/business/registerType";

export default {
  name: "RegisterNeed",
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      batchDateList: [],
      // 选中数组
      ids: [],
      // 时间选择器显示隐藏
      timePickerShow: false,
      // 年度编辑器显示隐藏
      yearPickerShow: false,
      // 当前选中的批次时间项
      currentBatchItem: {
        type: "startTime",
      },
      // 当前选中的批次年度项
      currentYearItem: {},
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 招生信息表格数据
      registerNeedList: [],
      //全选
      AllCheck: false,
      // 弹出层标题
      title: "",
      showType: 1, // 1: 招生信息, 2: 批次时间
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        registerDeptId: null,
        registerTypeId: null,
        registerEnter: null,
        batchNameList: null,
        batchDateList: null,
        durationNameList: null,
        durationMoneyList: null,
        deptPicture: null,
        deptVideo: null,
        deptDesc: null,
        registerCondition: null,
        needOpen: null, // 招生状态筛选
      },
      currYear: new Date().getFullYear(),
      // 表单参数
      form: {},
      stepActive: 1,
      // 已选择的招生批次
      batchList: [],
      // 遍历的招生批次
      batchNameList: [],
      durationList: [],
      durationNameList: [],
      // 表单校验
      rules: {
        id: [{ required: true, message: "主键不能为空", trigger: "blur" }],
        registerDeptId: [
          {
            required: true,
            type: "number",
            message: "进修科目不能为空",
            trigger: "blur",
          },
        ],
        registerTypeId: [
          {
            required: true,
            type: "number",
            message: "招生类型不能为空",
            trigger: "blur",
          },
        ],
        registerEnter: [
          { required: false, message: "最低录取资格不能为空", trigger: "blur" },
        ],
        batchNameList: [
          { required: true, message: "招生批次不能为空", trigger: "blur" },
        ],
        batchDateList: [
          { required: true, message: "招生截止时间不能为空", trigger: "blur" },
        ],
        durationNameList: [
          { required: true, message: "进修期限不能为空", trigger: "blur" },
        ],
        durationMoneyList: [
          { required: true, message: "进修费用不能为空", trigger: "blur" },
        ],
        deptPicture: [
          { required: false, message: "科室图片不能为空", trigger: "blur" },
        ],
        deptVideo: [
          { required: false, message: "科室视频不能为空", trigger: "blur" },
        ],
        deptDesc: [
          { required: false, message: "科室简介不能为空", trigger: "blur" },
        ],
        registerCondition: [
          { required: true, message: "招生要求不能为空", trigger: "blur" },
        ],
      },
      registerDeptList: [],
      registerTypeList: [],
      registerBatchList: [],
      registerDurationList: consts.registerDurationList,

      customShow: false,
      customDay: null,
      customDayOld: null,
      isSecretary: false,
    };
  },
  watch: {
    showType(val) {
      if (val == 2) {
        this.getbatch();
      }
    },
  },
  created() {
    // 带教秘书只编辑科室信息
    this.isSecretary = this.$store.getters.roles.indexOf("secretary") > -1;
    this.getList();
    //获取批次时间
    this.getbatch();
    this.listAllRegisterDept();
    this.listAllRegisterType();
  },
  methods: {
    getbatch() {
      batchListAll().then((response) => {
        this.batchDateList = response.data
          .map((item) => ({
            id: item.id,
            batch: item.registerMonth,
            startTime: item.startDate,
            endTime: item.endDate,
            registerStatus: item.registerStatus ?? 1, // 默认状态为开启
            registerYear: item.registerYear ?? this.currYear, // 默认年度为当前年份
          }))
          .reverse();
        this.registerBatchList = this.batchDateList.map((item) => ({
          name: item.batch,
        }));
      });
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    customOpen() {
      this.customDay = null;
      this.customShow = true;
    },
    customSubmit() {
      if (!this.customDay) {
        this.$message.error("请输入天数");
        return;
      }
      if (this.customDay <= 0) {
        this.$message.error("天数必须大于0");
        return;
      }
      this.registerDurationList.push({ name: this.customDay + "天" });
      this.durationNameList.push({
        name: this.customDay + "天",
        money: 0,
      });
      this.durationList.push(this.customDay + "天");
      this.customShow = false;
    },
    batchNameListChange(e) {
      if (e.length > 0) {
        this.form.batchNameList = e.join(",");
      } else {
        this.form.batchNameList = "";
      }
      // 保存当前的 batchNameList，以便在更新时保留已有的日期
      const oldBatchNameList = this.batchNameList;
      let batchNameList = [];
      for (let i = 0; i < e.length; i++) {
        const selectedBatch = this.batchDateList.find(
          (item) => item.batch === e[i]
        );
        batchNameList.push({
          name: e[i],
          date: selectedBatch
            ? [selectedBatch.startTime, selectedBatch.endTime]
            : "",
        });
      }
      this.batchNameList = batchNameList;
      // 如果选择了'无'，清空进修期限相关列表
      if (e.includes("无")) {
        this.durationList = [];
        this.durationNameList = [];
        this.form.durationNameList = "";
        this.form.durationMoneyList = "";
      }
    },
    durationNameListChange(e) {
      if (e.length > 0) {
        this.form.durationNameList = e.join(",");
      } else {
        this.form.durationNameList = "";
      }
      // 保存当前的 durationNameList，以便在更新时保留已有的费用
      const oldDurationNameList = this.durationNameList;
      let durationNameList = [];
      for (let i = 0; i < e.length; i++) {
        const existingDuration = oldDurationNameList.find(
          (item) => item.name === e[i]
        );
        durationNameList.push({
          name: e[i],
          money: existingDuration ? existingDuration.money : 0, // 如果存在，保留费用；否则，设置为0
        });
      }
      this.durationNameList = durationNameList;
    },
    /** 查询招生信息列表 */
    getList() {
      this.loading = true;
      listRegisterNeed(this.queryParams).then((response) => {
        this.registerNeedList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询科目是否有值
    handleDeptChange(val) {
      if (val) {
        listRegisterNeed({
          registerDeptId: val,
          pageNum: 1,
          pageSize: 10,
        }).then((response) => {
          if (response.rows.length > 0) {
            this.$message.error("当前进修科室已存在，请不要重复添加");
            this.form.registerDeptId = null;
          }
        });
      }
    },
    // 取消按钮
    cancel() {
      this.reset();

      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        registerDeptId: null,
        registerTypeId: null,
        registerEnter: null,
        batchNameList: null,
        batchDateList: null,
        durationNameList: null,
        durationMoneyList: null,
        deptPicture: null,
        deptVideo: null,
        deptDesc: null,
        registerCondition: null,
      };
      this.canselAllcheck();

      this.stepActive = 1;
      this.batchList = [];
      this.batchNameList = [];
      this.durationList = [];
      this.durationNameList = [];
      setTimeout(() => {
        this.resetForm("form1");
      }, 500);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.canselAllcheck();
      this.queryParams.pageNum = 1;
      this.getList();
    },
    canselAllcheck() {
      this.AllCheck = false;
      this.ids = [];
      this.single = true;
      this.multiple = true;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChangeAll(checked) {
      let ids = [];
      for (let i = 0; i < this.registerNeedList.length; i++) {
        // 使用 $set 确保属性被响应式地修改
        this.$set(this.registerNeedList, i, {
          ...this.registerNeedList[i],
          check: checked,
        });
        if (checked) {
          ids.push(this.registerNeedList[i].id);
        }
      }
      this.ids = ids;
      console.log(ids);
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
    // 多选框选中数据
    handleSelectionChange(checked, index) {
      this.$set(this.registerNeedList, index, {
        ...this.registerNeedList[index],
        check: checked,
      });

      let ids = [];
      for (let i = 0; i < this.registerNeedList.length; i++) {
        if (this.registerNeedList[i].check) {
          ids.push(this.registerNeedList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getbatch();
      this.open = true;
      this.title = "添加招生信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids;
      getRegisterNeed(id).then((response) => {
        this.form = response.data;
        // 批次
        this.batchList = response.data.batchNameList.split(",");
        let batchNameList = [];
        for (let i = 0; i < this.batchList.length; i++) {
          batchNameList.push({
            name: this.batchList[i],
            date: response.data.batchDateList
              ? response.data.batchDateList.split(",")[i].split("-")
              : "",
          });
        }
        this.batchNameList = batchNameList;
        // 时长、费用
        this.durationList = response.data.durationNameList.split(",");
        let durationNameList = [];
        let addDayList = [];
        for (let i = 0; i < this.durationList.length; i++) {
          if (this.durationList[i].indexOf("天") > -1) {
            addDayList.push({ name: this.durationList[i] });
          }
          durationNameList.push({
            name: this.durationList[i],
            money: response.data.durationMoneyList
              ? response.data.durationMoneyList.split(",")[i]
              : "",
          });
        }
        this.durationNameList = durationNameList;
        this.registerDurationList =
          consts.registerDurationList.concat(addDayList);
        // 科室负责人
        if (this.isSecretary) {
          this.stepActive = 2;
        }
        this.open = true;
        this.title = "修改招生信息";
      });
    },

    // 添加一个nextStep方法来处理下一步逻辑
    nextStep() {
      // 根据当前步骤验证不同的字段
      let valid = true;
      if (this.stepActive === 1) {
        let batchDateList = [];
        for (let i = 0; i < this.batchNameList.length; i++) {
          if (
            this.batchNameList[i].name !== "无" &&
            !this.batchNameList[i].date
          ) {
            this.$modal.msgError("招生时间不能为空");
            return;
          }
          if (
            this.batchNameList[i].date &&
            this.batchNameList[i].date[0].indexOf("00:00:00") == -1
          ) {
            this.batchNameList[i].date[0] =
              this.batchNameList[i].date[0] + " 00:00:00";
          }
          if (
            this.batchNameList[i].date &&
            this.batchNameList[i].date[1].indexOf("23:59:59") == -1
          ) {
            this.batchNameList[i].date[1] =
              this.batchNameList[i].date[1] + " 23:59:59";
          }
          if (this.batchNameList[i].date) {
            batchDateList.push(this.batchNameList[i].date.join("-"));
          }
          console.log(batchDateList);
        }
        this.form.batchDateList = batchDateList.join(",");
        this.$refs.form1.validateField("registerDeptId");
        this.$refs.form1.validateField("batchNameList");
        this.$refs.form1.validateField("durationNameList");

        this.$refs.form1.validate((validCallback) => {
          if (validCallback) {
            this.stepActive++;
          } else {
            this.$message.error("请填写所有必填项");
          }
        });
      } else if (this.stepActive === 2) {
        this.stepActive++;
      }
    },

    /** 提交按钮 */
    submitForm() {
      let durationNameList = [];
      let durationMoneyList = [];
      for (let i = 0; i < this.durationNameList.length; i++) {
        /* if (!this.durationNameList[i].money || this.durationNameList[i].money <= 0) {
          this.$modal.msgError('招生截止时间不能为空，且大于0')
          return
        } */
        durationNameList.push(this.durationNameList[i].name);
        durationMoneyList.push(this.durationNameList[i].money);
      }
      this.form.durationNameList = durationNameList.join(",");
      this.form.durationMoneyList = durationMoneyList.join(",");
      this.$refs["form1"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRegisterNeed(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegisterNeed(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 处理招生状态切换
    handleNeedStatusChange(row) {
      const newStatus = row.needOpen;
      const oldStatus = newStatus === 1 ? 0 : 1;

      // 恢复原状态，等待用户确认
      row.needOpen = oldStatus;

      const confirmText = newStatus === 1 ? "确定开启吗？" : "确定关闭吗？";

      this.$confirm(confirmText, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户确认，执行状态切换
          this.updateNeedStatus(row, newStatus);
        })
        .catch(() => {
          // 用户取消，保持原状态
          this.$message.info("已取消操作");
        });
    },
    // 更新招生状态
    async updateNeedStatus(row, status) {
      try {
        const data = {
          id: row.id,
          needOpen: status,
        };

        const response = await updateRegisterNeed(data);

        if (response.code === 200) {
          row.needOpen = status;
          this.$message.success(`招生状态已${status === 1 ? "开启" : "关闭"}`);

          // 刷新列表数据
          this.getList();
        } else {
          this.$message.error(response.msg || "操作失败");
        }
      } catch (error) {
        console.error("更新招生状态失败:", error);
        this.$message.error("操作失败，请重试");
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除招生信息的数据项？")
        .then(function () {
          return delRegisterNeed(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/registerNeed/export",
        {
          ...this.queryParams,
        },
        `registerNeed_${new Date().getTime()}.xlsx`
      );
    },
    // 处理更新时间
    handleUpdateTime(item, type) {
      this.currentBatchItem = { ...item, type: type };
      this.timePickerShow = true;
    },
    // 确认更新时间
    confirmUpdateTime() {
      const { id, startTime, endTime } = this.currentBatchItem;
      if (new Date(endTime) < new Date(startTime)) {
        this.$modal.msgError("结束时间不能小于开始时间");
        return;
      }
      const index = this.batchDateList.findIndex((item) => item.id === id);
      if (index > -1) {
        this.batchDateList[index].startTime = startTime;
        this.batchDateList[index].endTime = endTime;
      }
      // 这里可以添加API调用来更新后端数据
      updateBatchTime({
        id,
        registerMonth: this.currentBatchItem.batch,
        startDate: startTime,
        endDate: endTime,
      }).then(() => {
        this.$modal.msgSuccess("时间更新成功");
        this.timePickerShow = false;
        this.getbatch(); // 重新获取批次时间列表
      });
    },
    // 处理状态切换
    handleStatusChange(item) {
      const newStatus = item.registerStatus;
      const oldStatus = newStatus === 1 ? 0 : 1;

      // 恢复原状态，等待用户确认
      item.registerStatus = oldStatus;

      const confirmText = newStatus === 1 ? "确定开启吗？" : "确定关闭吗？";

      this.$confirm(confirmText, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户确认，执行状态切换
          this.updateBatchStatus(item, newStatus);
        })
        .catch(() => {
          // 用户取消，保持原状态
          this.$message.info("已取消操作");
        });
    },
    // 更新批次状态
    async updateBatchStatus(item, status) {
      try {
        const data = {
          id: item.id,
          registerStatus: status,
        };

        // 后端更新（沿用 updateBatchTime 接口）
        await updateBatchTime(data);

        // 更新本地状态
        item.registerStatus = status;
        this.$message.success(`批次状态已${status === 1 ? "开启" : "关闭"}`);

        // 刷新列表数据
        this.getbatch();
      } catch (error) {
        console.error("更新批次状态失败:", error);
        this.$message.error("操作失败，请重试");
      }
    },
    // 处理年度编辑
    handleUpdateYear(item) {
      this.currentYearItem = { id: item.id, registerYear: item.registerYear };
      this.yearPickerShow = true;
    },
    // 确认更新年度
    confirmUpdateYear() {
      const { id, registerYear } = this.currentYearItem;
      if (!registerYear || registerYear < 2000 || registerYear > 2100) {
        this.$modal.msgError("请输入有效的年度（2000-2100）");
        return;
      }
      const index = this.batchDateList.findIndex((item) => item.id === id);
      if (index > -1) {
        this.batchDateList[index].registerYear = registerYear;
      }
      // 后端更新（沿用 updateBatchTime 接口）
      updateBatchTime({ id, registerYear }).then(() => {
        this.$modal.msgSuccess("年度更新成功");
        this.yearPickerShow = false;
        this.getbatch(); // 重新获取批次时间列表
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.custom-table {
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #d8d8d8;
    padding: 20px 20px;
    min-width: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 14px;

    .w {
      height: 100%;
      display: flex;
    }

    .title {
      height: 100%;
    }

    .colc {
      font-weight: bolder;
      font-size: 14px;

      .desc {
        font-size: 12px;
        color: #888;
        margin-top: 10px;
        font-weight: normal;
        overflow: hidden;
        max-width: 250px;
        overflow: hidden;
        /* 隐藏超出的内容 */
        text-overflow: ellipsis;
        /* 使用省略号表示被隐藏的内容 */
        white-space: nowrap;
        /* 防止文本换行 */
      }
    }

    .colc:nth-child(1) {
      flex: 2;
      text-align: left;
    }

    .colc:nth-child(2) {
      flex: 6;
    }

    .colc:nth-child(3) {
      flex: 1;
      text-align: center;
      min-width: 120px;

      .desc {
        font-size: 12px;
        color: #999;
        margin-bottom: 10px;
        font-weight: normal;
      }
    }

    .colc:nth-child(4) {
      flex: 1;
      justify-content: space-between;
    }

    .w .col {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
  }

  .custom-dept:hover {
    border: 1px solid red;
  }
}

::v-deep .el-radio-button__orig-radio + .el-radio-button__inner {
  width: 140px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 140px;
}
</style>
